package utils

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"

	_ "github.com/mattn/go-sqlite3"
	logger "github.com/sirupsen/logrus"
	"xorm.io/core"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var Engine *Engines

type Engines struct {
	*xorm.Engine
}

func (e *Engines) InsertHistory(beans ...interface{}) (int64, error) {
	defer func() {
		ConnectInit()
		data, err := json.Marshal(beans)
		if err != nil {
			logger.Error(err)
			return
		}
		info := History{
			Name:   "FHST操作",
			Op:     fmt.Sprintf("添加 %s", string(data)),
			Common: "fhst op",
		}
		_, err = AddHistory(&info)
		if err != nil {
			logger.Error(err)
		}

	}()
	return e.Engine.Insert(beans...)
}

type History struct {
	Id     int64     `xorm:"id pk not null autoincr" name:"id"`
	Name   string    `xorm:"name" name:"name" verbose_name:"操作历史" list:"true"`
	Op     string    `xorm:"op" name:"op" verbose_name:"操作"`
	Common string    `xorm:"common" name:"common" verbose_name:"备注"`
	Create time.Time `xorm:"created"` //这个Field将在Insert时自动赋值为当前时间
	Update time.Time `xorm:"updated"` //这个Field将在Insert或Update时自动赋值为当前时间
}

func getByUUIDHistory(uuid string) (*History, bool, error) {
	data := new(History)
	has, err := Engine.Where("uuid = ?", uuid).Get(data)
	return data, has, err
}

func AddHistory(data *History) (int64, error) {
	affected, err := Engine.Insert(data)
	return affected, err
}

func DelHistory(id string) (int64, error) {
	data := new(History)
	affected, err := Engine.ID(id).Delete(data)
	return affected, err
}

func UpdateHistory(id string, data *History) (int64, error) {
	affected, err := Engine.Table(new(History)).ID(id).Update(data)
	return affected, err
}

func ConnectInit() {
	// 判断当前位置是否有utils文件夹
	if !IsPathExists(".fhst") {
		panic("未发现.fhst文件，请回到项目根目录")
	}

	rs, err := ReadFile(".fhst")
	if err != nil {
		panic(err)
	}

	pkgname := strings.Split(string(rs), ":")

	e, err := xorm.NewEngine("sqlite3", fmt.Sprintf("./%s.db", pkgname[1]))
	if err != nil {
		logger.Error(err.Error())
	}
	Engine = &Engines{Engine: e}
	Engine.ShowSQL(true)
	Engine.Logger().SetLevel(log.LogLevel(core.LOG_DEBUG))
	Engine.SetMaxIdleConns(300)
	Engine.SetMaxOpenConns(300)
	Engine.SetMapper(core.SnakeMapper{})
	// logger.Errorf("viper------------- is %s ",viper.GetString("snakemapper"))
	// tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, viper.GetString("snakemapper"))
	// Engine.SetTableMapper(tbMapper)
	Engine.SetColumnMapper(core.SameMapper{})

	logger.Debugf("读取项目数据库 %s.db", pkgname[1])

	err = Engine.Sync2(new(History))
	if err != nil {
		logger.Fatal(err.Error())
	}
}
